package testcase;

import org.opengauss.jdbc.PgConnection;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试最小连接模式，是否按照节点连接数量，升序排列。
 */
public class LeastConnLoadingBalanceTest {
  
  private final static String URL_DN3 = "jdbc:opengauss://192.168.0.243:14300/test";
  
  private final static String URL = "jdbc:opengauss://192.168.0.243:14100,192.168.0.243:14200,192.168.0.243:14300/test";
  
  private final static String LEASTCONN_PARAMS = "?autoBalance=leastconn";
  
  private final static String TARGET_SERVER_TYPE = "?autoBalance=leastconn&targetServerType=master";
  
  private final static String USERNAME = "test";
  
  private final static String PASSWORD = "huawei123.";
  
  // 向主备集群分批次插入连接，开启leastconn，观察各节点上的连接分布情况
  private static void testCreateConnectionAndCheckValidity() {
    Map<String, Integer> connectionMap = new ConcurrentHashMap<>();
    int num1 = 300;
    for (int i = 0; i < num1; i++) {
      try {
        PgConnection pgConnection = (PgConnection) DriverManager.getConnection(URL + LEASTCONN_PARAMS + "&loggerLevel=OFF", USERNAME, PASSWORD);
        String s = pgConnection.getSocketAddress().split("/")[1];
        connectionMap.put(s, connectionMap.getOrDefault(s, 0) + 1);
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
    System.out.println("向集群插入" + num1 + "个连接");
    System.out.println(connectionMap.toString());
  
    int num2 = 200;
    for (int i = 0; i < num2; i++) {
      try {
        PgConnection pgConnection = (PgConnection) DriverManager.getConnection(URL + TARGET_SERVER_TYPE + "&loggerLevel=OFF", USERNAME, PASSWORD);
        String s = pgConnection.getSocketAddress().split("/")[1];
        connectionMap.put(s, connectionMap.getOrDefault(s, 0) + 1);
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
    System.out.println("向主节点插入" + num2 + "个连接");
    System.out.println(connectionMap.toString());
  
    int num3 = 300;
    for (int i = 0; i < num3; i++) {
      try {
        PgConnection pgConnection = (PgConnection) DriverManager.getConnection(URL + LEASTCONN_PARAMS + "&loggerLevel=OFF", USERNAME, PASSWORD);
        String s = pgConnection.getSocketAddress().split("/")[1];
        connectionMap.put(s, connectionMap.getOrDefault(s, 0) + 1);
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }
    System.out.println("向集群插入" + num3 + "个连接");
    System.out.println(connectionMap.toString());
  }
  
  public static void main(String[] args) {
    testCreateConnectionAndCheckValidity();
  }
}
